package cn.huhst.cas.weisiqian.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.apache.log4j.Logger;

import cn.huhst.cas.weisiqian.dbhelp.DBHelper;
import cn.huhst.cas.weisiqian.pojo.Comment;

public class CommentDao {

	private Logger logger = Logger.getLogger(CommentDao.class);

	public boolean addComment(Comment comment) {
		boolean result = false;
		Connection connection = DBHelper.getConnection();
		PreparedStatement pstmt = null;
		String sql = "INSERT INTO comment(parentid,commenttype,content,author,writetime,likecount,dislikecount) value(?,?,?,?,?,?,?)";
		logger.info("sql:" + sql);
		int count = 0;
		try {
			pstmt = connection.prepareStatement(sql);
			pstmt.setInt(1, comment.getParentid());
			pstmt.setInt(2, comment.getCommenttype());
			pstmt.setString(3, comment.getContent());
			pstmt.setString(4, comment.getAuthor());
			pstmt.setDate(5, comment.getWritetime());
			pstmt.setInt(6, comment.getLikecount());
			pstmt.setInt(7, comment.getDislikecount());
			count = pstmt.executeUpdate();
			if (count > 0) {
				logger.info("添加" + comment + "成功");
				result = true;
			} else {
				logger.error("添加" + comment + "失败");
			}
		} catch (SQLException e) {
			logger.error("添加评论失败");
		} finally {
			DBHelper.closeDBHelp(connection, pstmt, null);
			logger.info("关闭数据库连接");
		}
		return result;
	}

	public boolean like(String commentid) {
		logger.info("commentid=" + commentid);
		boolean result = false;
		Connection connection = DBHelper.getConnection();
		PreparedStatement pstmt = null;
		int count = 0;
		String sql = "UPDATE comment SET likecount=likecount+1 WHERE commentid=?";
		try {
			pstmt = connection.prepareStatement(sql);
			pstmt.setString(1, commentid);
			count = pstmt.executeUpdate();
			if (count > 0) {
				logger.info("commentid=" + commentid + " 点赞数加一");
				result = true;
			} else {
				logger.error("更新点赞数失败");
			}
		} catch (SQLException e) {
			logger.error("跟新点赞数出错");
		} finally {
			DBHelper.closeDBHelp(connection, pstmt, null);
			logger.info("关闭数据库连接");
		}
		return result;
	}

	public boolean DisLike(String commentid) {
		logger.info("commentid=" + commentid);
		boolean result = false;
		Connection connection = DBHelper.getConnection();
		PreparedStatement pstmt = null;
		int count = 0;
		String sql = "UPDATE comment SET dislikecount=dislikecount+1 WHERE commentid=?";
		try {
			pstmt = connection.prepareStatement(sql);
			pstmt.setString(1, commentid);
			count = pstmt.executeUpdate();
			if (count > 0) {
				logger.info("commentid=" + commentid + " 讨厌数加一");
				result = true;
			} else {
				logger.error("更新讨厌数失败");
			}
		} catch (SQLException e) {
			logger.error("更新讨厌数出错");
		} finally {
			DBHelper.closeDBHelp(connection, pstmt, null);
			logger.info("关闭数据库连接");
		}
		return result;
	}

}
